﻿using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Prism.Mvvm;
using Revit.Async;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MVVM_Revit_Demo.RevitAsyncDemo
{
    public partial class RevitAsyncViewModel : BindableBase
    {
        void TestExe()
        {
            TaskDialog.Show("ok", "ok");
            ShowRvtPathFunc();
            GetFamiliesFunc(true);
        }

        public async void ShowRvtPathFunc()
        {
            await RevitTask.RunAsync(
              app =>
              {
                  string rvtName = app.ActiveUIDocument.Document.PathName;
                  TaskDialog.Show("RVT-PATH:", rvtName);
                  return null;
              });
            TaskDialog.Show("tips", "Done!");

        }


        public async void GetFamiliesFunc(object parameter)
        {
            var families = await RevitTask.RunAsync(
                app =>
                {
                    try
                    { 
                        string rvtName = app.ActiveUIDocument.Document.PathName;
                        TaskDialog.Show("GOOO", rvtName);
                        //在这里书写Revit API代码 
                        //这里利用了Lambda表达式创建的闭包上下文,
                        //使得我们可以访问按钮点击事件传入的参数，以及所有的局部变量
                        //假设点击按钮传入的是个bool值，用来指示是否过滤出可编辑的族
                        if (parameter is bool editable)
                        {
                            return new FilteredElementCollector(app.ActiveUIDocument.Document)
                                .Cast<Family>()
                                // .Where(family => editable ? family.IsEditable : true)
                                .ToList();
                        }
                        return null;
                    }
                    catch (Exception exp)
                    {
                        TaskDialog.Show("error", exp.ToString());
                        return null;
                    }

                });
            //注意上述内容由于无过滤条件仅仅为演示，可能导致revit奔溃  故使用try catch 作为保险
            TaskDialog.Show("tips", $"Family count: {families?.Count ?? 0}");

        }
         

    }
}
